package hydrap2p.gui.commands;

import java.util.ArrayList;

import hydrap2p.gui.FileTransferPanel;
import hydrap2p.gui.FilterLabelPanel;
import hydrap2p.gui.GUIDataHandler;
import hydrap2p.gui.GUIDownloadListing;

import javax.swing.JOptionPane;

public class Cmd_FileTransferPanel_EditFilterLabels implements Command {

	@Override
	public void execute() {
		//get a list of labels so we can add new ones if necessary
		ArrayList<String> labelList = FilterLabelPanel.getInstance().getLabels();
		
		// Put selected indices in a sortable list
		int[] indices = FileTransferPanel.getInstance().getTable().getSelectedRows();
		
		// For each row, pop up a window 
		GUIDownloadListing gdl;
		String labels;
		for(int i : indices){
			// TODO Change how the GDLs are accessed in the GUIDataHandler
			gdl = GUIDataHandler.getInstance().getDownloadListing().get(i);
			
			// Pull the current labels and format them
			labels = "";
			for(String s : gdl.getLabels()){
				labels += s.trim();
				labels += ";";
			}
			if(labels.length() > 0){
				labels = labels.substring(0, labels.length()-1);
			}
			
			// Show window, populate with current labels, and accept changes
			String newLabels = JOptionPane.showInputDialog(null, "Edit the labels for " + gdl.getName() + ".\n\nPlease separate the label entries with semicolons(;).", labels);
			if (newLabels != null)	//make sure they didn't press Cancel
			{
				// Clear the download's labels and put in the new ones
				gdl.getLabels().clear();
				for(String s : newLabels.split(";")){
					String trimmedLabel = s.trim();
					if(trimmedLabel.length() > 0){
						gdl.addLabel(trimmedLabel);
						
						if (!labelList.contains(trimmedLabel))
							labelList.add(trimmedLabel);
					}
				}
			}
			
			// Assign labels to download itself
			GUIDataHandler.getInstance().updateSharedItemLabels(gdl, newLabels);
			
		}
		
		
		//refresh the label panel and download list
		FilterLabelPanel.getInstance().updateLabelList();
		FileTransferPanel.getInstance().refreshDownloadList();
		
		System.out.println(getCommand());
		
	}

	@Override
	public String getCommand() {
		return this.getClass().getSimpleName();
	}

	@Override
	public void unexecute() {
		// TODO Auto-generated method stub

	}

}
